﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Emlyn.AudioToVideo.JobProcessorLib.Interfaces.Exceptions;
using System.Threading;

namespace Emlyn.AudioToVideo.JobProcessorLib.core.TestJobImpl
{
    public class TestJob: JobBase
    {
        Object _syncObj;
        Timer _timer;
        static int _progress;

        public TestJob() : base() { Init();  }

        public TestJob(string aJobID) : base(aJobID) { Init();  }

        private void Init()
        {
            _syncObj = new object();
            _timer = new Timer(new TimerCallback(TimerHandler));
            _progress = 0;
        }

        protected override bool CanStart()
        {
            int ldummy;

            return !String.IsNullOrEmpty(JobDetails) && Int32.TryParse(JobDetails, out ldummy);
        }

        protected override void StartJob()
        {
            if (!CanStart())
                throw new JobCannotStartException();

            lock (_syncObj)
            {
                if (_timer != null)
                {
                    _progress = 0;

                    int lintervalMSec;
                    if (!Int32.TryParse(JobDetails, out lintervalMSec))
                        lintervalMSec = 2000;

                    _timer.Change(lintervalMSec, lintervalMSec);
                }
            }
        }

        protected override void StopJob(bool aHalting)
        {
            lock (_syncObj)
            {
                if (_timer != null)
                    _timer.Change(Timeout.Infinite, Timeout.Infinite);
            }
        }

        void TimerHandler(object state)
        {
            try
            {
                lock (_syncObj)
                {
                    if (_timer != null)
                    {
                        _progress += 10;

                        Progress = _progress;

                        if (_progress >= 100)
                        {
                            _timer.Change(Timeout.Infinite, Timeout.Infinite); // stops this timer
                            SignalSuccess();
                        }
                        else
                        {
                            SignalProgressUpdate();
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                SetErrorMessage(ex.Message);
                SignalFailure();
            }
        }

        protected override void DoDispose()
        {
            lock (_syncObj)
            {
                if (_timer != null)
                {
                    _timer.Change(Timeout.Infinite, Timeout.Infinite);
                    _timer.Dispose();
                    _timer = null;
                }
            }
        }
    }
}
